package com.yzg.design;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author misterWei
 * @create 2020年05月16号:00点07分
 * @mailbox forcontinue@163.com
 * <p>
 * 使用park&unpark机制 使用三个线程 执行5次  abcabcabcabcabc
 */
@Slf4j(topic = "c.waitNotifyCrossOut")
public class ParkUnparkCrossOut {
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) throws InterruptedException {
        LoopPrint loopPrint = new LoopPrint();
        t1 = new Thread(() -> {
            loopPrint.printf("a", t2);
        }, "t1");

        t2 = new Thread(() -> {
            loopPrint.printf("b", t3);
        }, "t2");
        t3 = new Thread(() -> {
            loopPrint.printf("c", t1);
        }, "t3");
        t1.start();
        t2.start();
        t3.start();
        TimeUnit.SECONDS.sleep(2L);
        LockSupport.unpark(t1);
    }

    /**
     * a 0 1
     * b 1 2
     * c 2 3
     * .
     */
    static class LoopPrint {
       int loopNumber = 5;
        public void printf(String content,Thread next){
            for (int i = 0; i < loopNumber; i++) {
                LockSupport.park();
                System.out.print(content);
                LockSupport.unpark(next);
            }
        }

    }

}
